from flask import Blueprint, request, jsonify
from app import db
from models.production import Product, Bom, ProductionOrder
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

bp = Blueprint('production', __name__, url_prefix='/api/production')

@bp.route('/products', methods=['GET'])
@jwt_required()
def get_products():
    """获取产品列表"""
    try:
        products = Product.query.filter_by(is_deleted=False).all()
        return jsonify({
            'code': 200,
            'message': '获取产品列表成功',
            'data': [product.to_dict() for product in products]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取产品列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/products', methods=['POST'])
@jwt_required()
def create_product():
    """创建产品"""
    try:
        data = request.get_json()
        
        # 检查必需字段
        required_fields = ['name', 'code', 'unit']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查产品编码是否已存在
        existing_product = Product.query.filter_by(code=data['code']).first()
        if existing_product:
            return jsonify({
                'code': 400,
                'message': '产品编码已存在',
                'data': None
            }), 400
        
        # 创建新产品
        product = Product(
            code=data['code'],
            name=data['name'],
            specification=data.get('specification'),
            unit=data['unit'],
            category=data.get('category'),
            description=data.get('description')
        )
        
        db.session.add(product)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建产品成功',
            'data': product.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建产品失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/boms', methods=['POST'])
@jwt_required()
def create_bom():
    """创建BOM"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查必需字段
        required_fields = ['product_id', 'bom_items']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查产品是否存在
        product = Product.query.get(data['product_id'])
        if not product:
            return jsonify({
                'code': 400,
                'message': '产品不存在',
                'data': None
            }), 400
        
        # 创建BOM项
        bom_items_data = data['bom_items']
        for item_data in bom_items_data:
            item = Bom(
                product_id=data['product_id'],
                material_id=item_data['material_id'],
                quantity=item_data['quantity'],
                unit=item_data.get('unit', '件')
            )
            db.session.add(item)
        
        db.session.commit()
        
        # 查询创建的BOM项
        bom_items = Bom.query.filter_by(product_id=data['product_id']).all()
        
        return jsonify({
            'code': 200,
            'message': '创建BOM成功',
            'data': [item.to_dict() for item in bom_items]
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建BOM失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/orders', methods=['GET'])
@jwt_required()
def get_orders():
    """获取生产订单列表"""
    try:
        # 获取查询参数
        status = request.args.get('status')
        product_id = request.args.get('product_id')
        
        # 构建查询
        query = ProductionOrder.query.filter_by(is_deleted=False)
        
        if status:
            query = query.filter_by(status=status)
            
        if product_id:
            query = query.filter_by(product_id=product_id)
            
        orders = query.all()
        
        return jsonify({
            'code': 200,
            'message': '获取生产订单列表成功',
            'data': [order.to_dict() for order in orders]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取生产订单列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/orders/<int:order_id>', methods=['GET'])
@jwt_required()
def get_order(order_id):
    """获取生产订单详情"""
    try:
        order = ProductionOrder.query.get(order_id)
        if not order or order.is_deleted:
            return jsonify({
                'code': 404,
                'message': '生产订单不存在',
                'data': None
            }), 404
            
        return jsonify({
            'code': 200,
            'message': '获取生产订单详情成功',
            'data': order.to_dict()
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取生产订单详情失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/orders', methods=['POST'])
@jwt_required()
def create_order():
    """创建生产订单"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查必需字段
        required_fields = ['product_id', 'quantity', 'planned_start_date', 'planned_end_date']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查产品是否存在
        product = Product.query.get(data['product_id'])
        if not product:
            return jsonify({
                'code': 400,
                'message': '产品不存在',
                'data': None
            }), 400
        
        # 创建订单
        order = ProductionOrder(
            order_no=f"PO{datetime.now().strftime('%Y%m%d%H%M%S')}",  # 简单的订单号生成
            product_id=data['product_id'],
            quantity=data['quantity'],
            planned_start_date=datetime.strptime(data['planned_start_date'], '%Y-%m-%d').date() if isinstance(data['planned_start_date'], str) else data['planned_start_date'],
            planned_end_date=datetime.strptime(data['planned_end_date'], '%Y-%m-%d').date() if isinstance(data['planned_end_date'], str) else data['planned_end_date'],
            remarks=data.get('remarks'),
            created_by=current_user_id
        )
        
        db.session.add(order)
        db.session.commit()
        
        # 重新查询以获取完整数据
        order = ProductionOrder.query.get(order.id)
        
        return jsonify({
            'code': 200,
            'message': '创建生产订单成功',
            'data': order.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建生产订单失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/orders/<int:order_id>/status', methods=['PUT'])
@jwt_required()
def update_order_status(order_id):
    """更新生产订单状态"""
    try:
        order = ProductionOrder.query.get(order_id)
        if not order:
            return jsonify({
                'code': 404,
                'message': '生产订单不存在',
                'data': None
            }), 404
            
        data = request.get_json()
        status = data.get('status')
        
        if not status:
            return jsonify({
                'code': 400,
                'message': '缺少状态参数',
                'data': None
            }), 400
            
        # 更新状态
        order.status = status
        
        # 如果是完成状态，设置完成时间
        if status == 'COMPLETED':
            order.actual_end_date = datetime.now()
        elif status == 'IN_PROGRESS':
            order.actual_start_date = datetime.now()
            
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新订单状态成功',
            'data': order.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'更新订单状态失败: {str(e)}',
            'data': None
        }), 500